package pluginMain;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.event.Event.Result;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryDragEvent;
import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.event.player.PlayerPickupItemEvent;
import org.bukkit.inventory.ItemStack;

public class PlayerEventHandler implements Listener {
	public void actionFail(Player player, ItemStack itemStack) {
		player.sendMessage(
				ChatColor.translateAlternateColorCodes('&', "&6您无法操作该物品:" + itemStack.getItemMeta().getDisplayName()));
	}

	@EventHandler(priority = EventPriority.HIGHEST)
	public void onPlayerInventory(InventoryDragEvent event) {
		if (event.getWhoClicked().isOp())
			return;

		if (isBindItem(event.getCursor())) {
			actionFail((Player) event.getWhoClicked(), event.getCursor());
			cancelAndDeny(event);
		}

		if (isBindItem(event.getOldCursor())) {
			actionFail((Player) event.getWhoClicked(), event.getOldCursor());
			cancelAndDeny(event);
		}

		for (ItemStack itemStack : event.getNewItems().values())
			if (isBindItem(itemStack)) {
				actionFail((Player) event.getWhoClicked(), itemStack);
				cancelAndDeny(event);
			}

	}

	public void cancelAndDeny(InventoryDragEvent event) {
		event.setCancelled(true);
		event.setResult(Result.DENY);

	}

	@EventHandler(priority = EventPriority.HIGHEST)
	public void onPlayerDropItem(PlayerDropItemEvent event) {
		if (!event.getPlayer().isOp() || isBindItem(event.getItemDrop().getItemStack())) {
			if (isBindItem(event.getItemDrop().getItemStack())) {
				actionFail(event.getPlayer(), event.getItemDrop().getItemStack());
			}

		}
	}

	@EventHandler(priority = EventPriority.HIGHEST)
	public void onPlayerPick(PlayerPickupItemEvent event) {
		if (!event.getPlayer().isOp() || isBindItem(event.getItem().getItemStack())) {
			event.setCancelled(true);
		}
	}

	public static boolean isBindItem(ItemStack itemStack) {
		for (String lore : itemStack.getItemMeta().getLore()) {
			if (lore.matches(BAKABinder.LoreBind)) {
				return true;
			}
		}
		return false;
	}

}
